package Class抽象类接口;
//模拟实现一个排序

import java.util.Arrays;
import java.util.Comparator;

//先学习怎么排序
class Student implements Comparable<Student> {
    String name;
    int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
    @Override
    public int compareTo(Student o) {
        return this.age - o.age;
    }
}

class AgeComparable implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.age - o2.age;
    }
}

class NameComparable implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);
    }
}
public class Test_4_111 {
    public static void my_sort(Comparable[] comparables) {
        for (int i = 0; i < comparables.length; i++) {
            for (int j = 0; j < comparables.length-1-i; j++) {
                if(comparables[j].compareTo(comparables[j+1]) < 0) {
                    Comparable tmp = comparables[j];
                    comparables[j] = comparables[j+1];
                    comparables[j+1] = tmp;
                }
            }
        }
    }
    public static void main(String[] args) {
        Student student1 = new Student("zhangsan",16);
        Student student2 = new Student("lisi",49);
        Student student3 = new Student("wangwu",46);
        Student[] students = {student1,student2,student3};

        //传入的元素要是compare接口的，然后才能实现比较功能
        Arrays.sort(students);
        System.out.println(Arrays.toString(students));
        my_sort(students);
        System.out.println(Arrays.toString(students));
        //上面的只能根据年龄或者姓名比较，且不方便随时更改
        //我们再定义一个接口（排序构造器）使得程序更灵活~
        System.out.println("__________________________________");
        System.out.println("根据年龄排序");
        AgeComparable age = new AgeComparable();
        System.out.println(age.compare(student1, student2));
        System.out.println("根据姓名排序");
        NameComparable name = new NameComparable();
        System.out.println(name.compare(student1, student2));

        //使用排序构造器来排序数组
        System.out.println("使用年龄构造器进行排序");
        AgeComparable ageComparable2 = new AgeComparable();
        Arrays.sort(students,ageComparable2);
        System.out.println(Arrays.toString(students));
        System.out.println("使用姓名构造器进行排序");
        NameComparable nameComparable2 = new NameComparable();
        Arrays.sort(students,nameComparable2);
        System.out.println(Arrays.toString(students));
    }
}
